<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:insert="common/header :: head"></head>
<!-- 班级管理 -->
<body>
<div id="app">
  <template>
    <el-row>
      <el-col :span="4">
        <div style="width: 180px;">
          <el-select size="small" v-model="selectMajor" placeholder="专业">
            <el-option v-for="(major,index) in majors" :key="index" :label="major" :value="major"></el-option>
          </el-select>
        </div>
      </el-col>
      <el-col :span="4">
        <el-select size="small" style="width: 180px;" v-model="selectYear" placeholder="年级">
          <el-option v-for="(year,index) in years" :key="index" :label="year" :value="year">
          </el-option>
        </el-select>
      </el-col>
      <el-col :span="5">
        <el-select size="small" style="width: 250px;" v-model="selectCounselor" placeholder="辅导员工号">
          <el-option label="全部" value="全部"></el-option>
          <el-option v-for="item in systemUsers" :key="item.value" :label="item.value + ' '+ item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-col>

      <el-col :span="1.5">
        <el-button size="small" type="primary" style="margin: 0px 10px 15px" @click="search">查询</el-button>
      </el-col>
      <el-col :span="2">
        <el-button size="small" type="primary" @click="agreeAdd()" style="margin: 0px 10px 15px">新增班级</el-button>
      </el-col>
      <el-col :span="2">
        <el-button size="small" type="primary" @click="[sedialogFormVisible = true]">批量添加</el-button>
      </el-col>
      <el-col :span="2" style="padding-top: 8px;">
        <a href="../classInfo/downLoadTemplate">下载模板</a>
      </el-col>
    </el-row>


    <el-dialog title="批量添加辅导员带班信息" :visible.sync="sedialogFormVisible" width="35%" height="110%">
      <el-form style="display: inline-block;margin-left: 30px">
        <el-upload class="upload-demo" ref="upload" multiple accept=".xls,.xlsx"
                   action="" :auto-upload="false" :show-file-list="true" :on-success="endUpload" :on-error="errorUp"
                   :before-upload="beforeUpload" :http-request="uploadFile">
          <el-button size="small" slot="trigger" type="primary">选择文件</el-button>
          <div slot="tip" style="color: red;">请上传文件大小不超过2MB,格式为 .xls类型的文件</div>
        </el-upload>
      </el-form>
      <p style="margin-top: 20px;">请先下载模板文件填写再上传，且一次只能上传一个文件。</p>
      <div slot="footer" class="dialog-footer" style="display: flex">
        <el-button size="small" type="primary" @click="submitUploadList">确 定</el-button>
        <el-button size="small" @click="sedialogFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>


    <el-dialog title="新增班级" :visible.sync="addDialogFormVisible" :modal="false" :close-on-click-modal="false"
               :close-on-press-escape="false" center width="460px">
      <el-form label-width="80px" label-position="left" ref="ruleForm" :model="ruleForm">
        <el-form-item label="班级名称" prop="tname">
          <el-input placeholder="请输入班级名称" style="width: 280px;" type="text" v-model="ruleForm.cname"></el-input>
        </el-form-item>
        <el-form-item label="辅导员" prop="tname">
          <el-select v-model="ruleForm.counselor" style="width: 280px;" placeholder="辅导员工号">
            <el-option v-for="item in systemUsers" :key="item.value" :label="item.value+' '+item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" type="primary" @click="addDepartment('ruleForm')">确 定</el-button>
        <el-button size="small" @click="addDialogFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>
    <div style="margin-top: -25px;">
      <el-divider></el-divider>
    </div>

    <el-table ref="multipleTable" v-loading="loading" :data="tableData.list" tooltip-effect="dark" style="width: 100%;border: 1px;margin-top: -15px;">
      <el-table-column fixed min-width="20%" label="序号" align="center" prop="id"></el-table-column>
      <el-table-column prop="cname" label="名称" min-width="20%" align="center"></el-table-column>
      <el-table-column prop="counselorName" label="辅导员工号" min-width="20%" align="center"></el-table-column>
      <el-table-column prop="count" label="班级人数" min-width="20%" align="center"></el-table-column>
      <el-table-column fixed="right" label="操作" min-width="20%" align="center">
        <template slot-scope="scope">
          <el-button size="small" type="primary"
                     @click="undataDialogFormVisible=true;getValue(scope.row)">修改</el-button>

          <el-dialog title="修改班级信息" :visible.sync="undataDialogFormVisible" :modal="false"
                     :close-on-click-modal="false" :close-on-press-escape="false" width="460px">
            <el-form label-width="80px" label-position="left">
              <el-form-item label="班级名称">
                <template>
                  <el-input type="text" style="width: 280px;"  v-model="updatatname" placeholder="请输入班级名称"></el-input>
                </template>
              </el-form-item>
              <el-form-item label="辅导员">
                <el-select v-model="updateacid" style="width: 280px;"  placeholder="辅导员工号">
                  <el-option v-for="item in systemUsers" :key="item.value" :label="item.value + ' '+ item.label" :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button size="small" type="primary" @click="upData()">确 定</el-button>
              <el-button size="small" @click="undataDialogFormVisible = false">取 消</el-button>
            </div>
          </el-dialog>
        </template>
      </el-table-column>
    </el-table>

    <div class="block" style="margin-top: 10px;">
      <span class="demonstration"></span>
      <el-pagination
              @current-change="handleCurrentChange"
              layout="total, prev, pager, next, jumper"
              :current-page="currentPage"
              :page-size="pageSize"
              :total="tableData.total"
              :pager-count="5"
              align="center">
      </el-pagination>
    </div>
</template>
</div>
<script type="text/javascript">
  let urlBase = "../classInfo/";
  var v = new Vue({
    el: "#app",
    data: {
      currentPage: 1, //当前页码
      total: '',      //总条数，后面会换成动态的
      pageSize: 10, 	//每页的总条数
      tableData: [{
        tid: '',
        tname: ''
      }],//表单值
      // 页面加载效果
      loading: false,
      //删除框
      deleteDialogFormVisible: false,
      //增加框
      addDialogFormVisible: false,
      //修改框
      undataDialogFormVisible: false,
      //对话框 宽度
      formLabelWidth: '240px',
      //删除所需要的id值
      rowId: '',
      //表单数据
      formData: new FormData(),
      //新增框中的班级值
      ruleForm: {cname: '', counselor: ''},
      //修改框中所需要的id值
      updatatid: '',
      //修改框中所需要的班级值
      updatatname: '',
      //辅导员工号
      updateacid: '',
      //所有的辅导员信息
      systemUsers: [],
      //筛选条件中所有的专业信息
      majors: [],
      years: [],
      //筛选条件中的所选择的年份
      selectYear: '',
      //筛选条件中所选择的专业
      selectMajor: '',
      //初始状态下上传文件框是否显示
      sedialogFormVisible: false,
      //删除班级的提示信息
      deleteContent: '',
      //修改数据时原数据
      oldValue: '',
      //筛选的辅导员
      selectCounselor: ''
    },
    methods: {
      //获取行值
      getValue: function (row) {
        this.updatatid = row.id;
        this.updatatname = row.cname;
        this.updateacid = row.counselor;
        this.oldValue = row.cname;
      },
      //修改学院
      upData: function () {
        if (this.updatatname === '') {
          this.$message({message: "请输入班级名称", type: 'warning'})
        }
        const regCN = /(\p{Unified_Ideograph}|[0-9]|[a-zA-Z])/u;
        if (!regCN.test(this.updatatname)) {
          this.$message({message: "班级名称不能包含特殊字符", type: 'warning'})
        } else {
          if (this.oldValue == this.updatatname) {
            axios.get("../classInfo/update?cname=" + this.updatatname + "&id=" + this.updatatid + "&counselor=" + this.updateacid).then(response => {
              if (response.data.code == 1) {
                this.showAll();
                const m = this.$message({message: "修改成功", type: 'success'})
                setTimeout(() => {
                  m.close()
                }, 1000)
              } else {
                const m = this.$message({message: "修改失败", type: 'warning'})
                setTimeout(() => {
                  m.close()
                }, 1000)
              }
              this.undataDialogFormVisible = false;
            })
          } else {
            axios.get("../classInfo/queryByName?cname=" + this.updatatname).then(res => {
              if (res.data.data == null) {
                axios.get("../classInfo/update?cname=" + this.updatatname + "&id=" + this.updatatid + "&counselor=" + this.updateacid).then(response => {
                  if (response.data.code == 1) {
                    this.showAll();
                    const m = this.$message({message: "修改成功", type: 'success'})
                    setTimeout(() => {
                      m.close()
                    }, 1000)
                  } else {
                    const m = this.$message({message: "修改失败", type: 'warning'})
                    setTimeout(() => {
                      m.close()
                    }, 1000)
                  }
                  this.undataDialogFormVisible = false;
                })
              } else {
                this.$message({message: "班级名重复，请重新命名班级", type: 'warning'})
              }
            })
          }

        }
      }
      ,
      //同意增加框出现
      agreeAdd: function () {
        this.addDialogFormVisible = true;
      }
      ,
      //重置表单
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
      ,
      //添加班级
      addDepartment: function (formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            const regCN = /(\p{Unified_Ideograph}|[0-9]|[a-zA-Z])/u;
            if (!regCN.test(this.ruleForm.cname)) {
              this.$message({message: "班级名称不能包含特殊字符", type: 'warning'})
            } else if (!this.ruleForm.cname || !this.ruleForm.counselor) {
              this.$message({message: "班级名称或者辅导员工号不能为空", type: 'warning'})
            } else {
              axios.get("../classInfo/queryByName?cname=" + this.ruleForm.cname).then(res => {
                if (res.data.data != null) {
                  this.$message({message: "班级名重复，请重新命名班级", type: 'warning'})
                } else {
                  this.ruleForm.status = 1
                  axios.post("../classInfo/add", this.ruleForm).then(response => {
                    if (response.data.code == 1) {
                      this.showAll();
                      this.formData = new FormData();
                      this.resetForm(formName);
                      const m = this.$message({message: "添加成功", type: 'success'})
                      setTimeout(() => {
                        m.close()
                      }, 1000)
                      this.ruleForm = {cname: '', counselor: ''}
                      this.addDialogFormVisible = false;
                    } else {
                      this.formData = new FormData();
                      this.resetForm(formName);
                      const m = this.$message({message: response.data.msg, type: 'warning'})
                      setTimeout(() => {
                        m.close()
                      }, 1000)
                    }

                  })
                }
              })
            }
          }
        })
      }
      ,
      // 当前页改变时触发 跳转其他页
      handleCurrentChange: function (val) {
        this.currentPage = val;
        this.search()
        this.isChoose = false
      }
      ,
      //显示管理界面
      showAll: function () {
        this.$data.loading = true;
        this.search()

        axios.get("../api/user/getCounselor").then(res => {
          var data = res.data.data
          this.systemUsers = []
          for (let i = 0; i < data.length; i++) {
            let sys = {
              label: data[i].nickname,
              value: data[i].username
            }
            this.systemUsers.push(sys)
          }
        })

        //获得下拉框中所有的数据
        axios.get("../classInfo/getSelectInfo?teacherId=1").then(res => {
          if (res.data.code) {
            this.majors = res.data.data.majors
            this.majors.push('全部')
            this.years = res.data.data.years
            this.years.push('全部')
          } else {
            this.$message({message: res.data.msg, type: 'warning'});
          }
        })
      }
      ,
      search() {
        var major = this.selectMajor === '全部' ? '' : this.selectMajor
        var year = this.selectYear === '全部' ? '' : this.selectYear
        var counselor = this.selectCounselor === '全部' ? '' : this.selectCounselor
        if(major != '' || year != '' ||counselor != ''){
          this.currentPage = 1
        }
        axios.get("../classInfo", {
          params: {
            pageNum: this.currentPage,
            pageSize: this.pageSize,
            cname: major,
            yearnumber: year,
            counselor: counselor
          }
        }).then(response => {
          if (response.data.code == 1) {
            this.tableData = response.data.data;
          } else {
            this.$message({message: response.data.msg, type: 'warning'});
          }
          this.$data.loading = false;
        })
      }
      ,
      //before-upload 上传文件前
      beforeUpload: function (file) {
        if (['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'].indexOf(file.type) == -1 && ['application/vnd.ms-excel'].indexOf(file.type) == -1) {
          this.$message.error({message: "请上传.xlsx和.xls格式的文件", type: 'error'});
          return false;
        }
      }
      ,
      //上传失败调用
      errorUp: function (err) {
        this.$message({message: err, type: "error"})
      }
      ,
      //上传成功调用
      endUpload: function () {
        this.showAll()
      }
      ,
      // 解析模板
      async uploadFile(param) {
        const File = param.file;
        const service = axios.create({})
        let formData = new FormData()
        formData.append("file", File);
        this.$message({message: "数据添加中请稍后!", type: "warning"});
        const res = await service({
          url: urlBase + 'upload',
          method: 'POST',
          transformRequest: [function (data, headers) {
            // 去除post请求默认的Content-Type
            delete headers.post['Content-Type']
            return data
          }],
          data: formData
        }).then(res => {
          if (res.data.code == 1) {
            this.showAll();
            this.sedialogFormVisible = false;
            this.$message({message: '上传成功', type: "success"});
          } else {
            this.$message({showClose: true, duration: 0, message: res.data.msg, type: "error"});
          }
        })
      }
      ,
      //提交后跳转到:http-request
      submitUploadList: function () {
        const files = this.$refs.upload.uploadFiles[0];

        let size2M = files.size / 1024 / 1024 < 2;
        if (!size2M) {
          this.$message.warning('上传大小不能超过2M!');
          return false;
        }

        if (files >= 0) {
          this.$message({message: "请选择文件后再点确定", type: "warning"})
        } else {
          this.$refs.upload.submit()
        }
      }
      ,
    },
    created: function () {
      axios.all([this.showAll()]);
    },
  })
</script>

</body>
</html>